package demo.server.run;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import org.jconfig.Configuration;
import org.jconfig.ConfigurationManager;
import org.jconfig.handler.XMLFileHandler;

import demo.server.common.ServerConstant;

public class ServerConfig {
	
	private static Configuration config = null;
	
	public void loadConfig(){
		ConfigurationManager cm = ConfigurationManager.getInstance();
		String path = ServerConstant.configParth + File.separator + "serverLib";
		try {
			File file = new File(path);
			if (!file.exists()) {
				file.mkdirs();
			}
			
			file = new File(path + File.separator + "ServerConfig.xml");
			if (!file.exists()) {
				createFileConfig(file);
			}
			XMLFileHandler xmlf = new XMLFileHandler();
			xmlf.setFile(file);
			cm.load(xmlf, "ServerConfig.xml");
		} catch (Exception e) {
			e.printStackTrace();
			
		}
	}
	
	public void reloadConfig(){
		config = ConfigurationManager.getConfiguration("ServerConfig.xml");
	}
	
	public static Configuration getConfig(){
		if (config == null) {
			config = ConfigurationManager.getConfiguration("ServerConfig.xml");
		}
		return config;
	}
	
	private void createFileConfig(File file) throws IOException{
		BufferedWriter bw = new BufferedWriter(new FileWriter(file));
		bw.write("<?xml version=\"1.0\" ?>");
        bw.newLine();
        bw.write("\t<properties>");
        bw.newLine();
        bw.write("\t\t<category name=\"SOCKET\">");
//        bw.newLine();
//        bw.write("\t\t\t<property name=\"SERVER_ADDRESS\" value=\"localhost\"/>");
        bw.newLine();
        bw.write("\t\t\t<property name=\"PORT\" value=\"1234\"/>");
        bw.newLine();
        bw.write("\t\t\t<property name=\"TIME_IDLE\" value=\"60000\"/>");
        bw.newLine();
        bw.write("\t\t\t<property name=\"MAX_LIMIT\" value=\"4\"/>");
        bw.newLine();
        bw.write("\t\t\t<property name=\"AUTO_COMMIT\" value=\"false\"/>");
        bw.newLine();
        bw.write("\t\t</category>");
        bw.newLine();
        bw.write("\t</properties>");
        bw.flush();
        bw.close();
	}
}
